<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="资源名称" prop="resName">
            <el-input v-model="queryParams.resName" placeholder="请输入资源名称" clearable @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="资源状态" clearable>
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:res:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-if="refreshTable" v-loading="loading" :data="resList" row-key="id" :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
         <el-table-column prop="resName" label="资源名称" :show-overflow-tooltip="true" width="160"></el-table-column>
         <el-table-column prop="resType" label="资源类型" width="60"></el-table-column>
         <el-table-column prop="permission" label="权限标识" align="center" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
               <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                  @change="handleStatusChange(scope.row)"></el-switch>
            </template>
         </el-table-column>
         <el-table-column prop="resSort" label="排序" width="60"></el-table-column>
         <el-table-column label="创建时间" align="center" prop="createdTime">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createdTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:res:update']">修改</el-button>
               <el-button type="text" icon="Plus" @click="handleAdd(scope.row)"
                  v-hasPermi="['system:res:add']">新增</el-button>
               <el-button type="text" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:res:delete']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- 添加或修改资源对话框 -->
      <el-dialog :title="title" v-model="open" width="680px" append-to-body>
         <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
               <el-col :span="24">
                  <el-form-item label="上级资源">
                     <el-tree-select v-model="form.parentId" :data="resOptions" :check-strictly="true"
                        :props="{ value: 'id', label: 'resName', children: 'children' }" value-key="id"
                        placeholder="选择上级资源" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="资源类型" prop="resType">
                     <el-radio-group v-model="form.resType">
                        <el-radio label="目录">目录</el-radio>
                        <el-radio label="页面">页面</el-radio>
                        <el-radio label="按钮">按钮</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="资源名称" prop="resName">
                     <el-input v-model="form.resName" placeholder="请输入资源名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="resSort">
                     <el-input-number v-model="form.resSort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item>
                     <el-input v-model="form.permission" placeholder="请输入权限标识" maxlength="100" />
                     <template #label>
                        <span>
                           <el-tooltip content="系统定义的权限规则如: system:user:create"
                              placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           权限字符
                        </span>
                     </template>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="res">
import { createOne, deleteOne, queryOne, queryList, updateOne } from "@/api/system/res";

const { proxy } = getCurrentInstance();
// const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");
const sys_normal_disable = ref([
   {
      value: 1,
      label: "启用",
   },
   {
      value: 0,
      label: "未启用",
   },
]);
const resList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const resOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);

const data = reactive({
   form: {
      id: undefined,
      resName: undefined,
      resType: undefined,
      parentId: undefined,
      resSort: 0,
      permission: undefined
   },
   queryParams: {
      resName: undefined,
      sortBy: 'resSort',
      pageNum: 1,
      pageSize: 999,
   },
   rules: {
      resName: [{ required: true, message: "资源名称不能为空", trigger: "blur" }],
      resSort: [{ required: true, message: "资源顺序不能为空", trigger: "blur" }]
   },
});

const { queryParams, form, rules } = toRefs(data);

// 修改状态
function handleStatusChange(row) {
   const data = row
   let text = row.status === 0 ? "停用" : "启用";
   proxy.$modal
      .confirm('确认要"' + text + '""' + row.resName + '吗?')
      .then(function () {
         return updateOne(data);
      })
      .then(() => {
         proxy.$modal.msgSuccess(text + "成功");
      })
      .catch(function () {
         row.status = row.status === "0" ? "1" : "0";
      });
}

/** 查询资源列表 */
function getList() {
   loading.value = true;
   queryList(queryParams.value).then(response => {
      response.content.forEach(element => {
         element.parentId = element.parent?.id
      });
      resList.value = proxy.handleTree(response.content, "id");
      console.log(resList.value)
      loading.value = false;
   });
}
/** 查询资源下拉树结构 */
function getTreeselect() {
   resOptions.value = [];
   queryList(queryParams.value).then(response => {
      response.content.forEach(element => {
         element.parentId = element.parent?.id
      });
      const res = { id: 0, resName: "主类目", children: [] };
      res.children = proxy.handleTree(response.content, "id");
      resOptions.value.push(res);
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      resName: undefined,
      resType: undefined,
      parentId: undefined,
      resSort: 0,
      permission: undefined
   };
   proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   getTreeselect();
   // fix 选择直接指定
   if (row != null && row.id) {
      form.value.parentId = row.id;
   } else {
      form.value.parentId = 0;
   }
   open.value = true;
   title.value = "添加资源";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
   refreshTable.value = false;
   isExpandAll.value = !isExpandAll.value;
   nextTick(() => {
      refreshTable.value = true;
   });
}
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   await getTreeselect();
   queryOne(row.id).then(response => {
      form.value = response;
      // fix 更新
      if (response.parent != null) {
         form.value.parentId = response.parent.id;
      } else {
         form.value.parentId = 0;
      }

      open.value = true;
      title.value = "修改资源";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["formRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            updateOne(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            createOne(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}
/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.resName + '"的数据项?').then(function () {
      return deleteOne(row.id);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

getList();
</script>
